﻿using System;
using Microsoft.Win32;
using SimpleSpreadsheet.Framework;
using SimpleSpreadsheet.Model;

namespace SimpleSpreadsheet.ViewModels
{
    /// <summary>
    /// Workbook ViewModel capable of activating and displaying one view (Screen)
    /// </summary>
    public class WorkbookViewModel : Conductor<object>
    {
        public WorkbookViewModel(ShellViewModel shellViewModel, int rows, int columns)
        {
            ShellViewModel = shellViewModel;
            Workbook = new Workbook();
            ShowWorksheet(rows, columns);
        }

        public Workbook Workbook { get; private set; }
        public ShellViewModel ShellViewModel { get; private set; }
        public WorksheetViewModel CurrentWorksheetViewModel { get; private set; }

        /// <summary>
        /// Shows a worksheet
        /// </summary>
        /// <param name="rows"></param>
        /// <param name="columns"></param>
        public void ShowWorksheet(int rows, int columns)
        {
            CurrentWorksheetViewModel = new WorksheetViewModel(rows, columns);
            ActivateItem(CurrentWorksheetViewModel);
        }

        /// <summary>
        /// Open new document
        /// </summary>
        public void NewDocument(object viewModel, object[] args)
        {
            CurrentWorksheetViewModel.New();
        }

        /// <summary>
        /// Loads the document
        /// </summary>
        /// <param name="viewmodel"></param>
        /// <param name="args"></param>
        public void LoadDocument(object viewmodel, object[] args)
        {
            var path = args[0] as string;
            CurrentWorksheetViewModel.Load(path);
        }

        /// <summary>
        /// Displays the 'save file' dialog and calls worksheet to save the document
        /// </summary>
        public void SaveDocument()
        {
            // New document
            if (String.IsNullOrEmpty(CurrentWorksheetViewModel.FileName))
            {
                var dlg = new SaveFileDialog {DefaultExt = ".txt", Filter = "Text documents (.txt)|*.txt"};
                bool? result = dlg.ShowDialog();

                if (result == true)
                {
                    CurrentWorksheetViewModel.FileName = dlg.FileName;
                    CurrentWorksheetViewModel.Save();
                }
            }
                // Opened document
            else
            {
                CurrentWorksheetViewModel.Save();
            }
        }
    }
}